import { ActionLogOta } from "@/entity/actionLogOta.entity";
import { OtaTask } from "@/entity/otaTask.entity";
import { Repository } from "typeorm";
import { updateGw } from "./gateway";
import { Gateway } from "@/entity/gateway.entity";
import { updateWristband } from "./wristband";
import { Wristband } from "@/entity/wristband.entity";

export async function createActionLog(ota_action_log: Partial<ActionLogOta> & Partial<Wristband>, otaTaskRepo: Repository<OtaTask>, gatewayRepo: Repository<Gateway>, wristbandRepo: Repository<Wristband>, actionLogRepo: Repository<ActionLogOta>) {
  let { taskid, fw_name, fw_version, gw_mac, wb_mac, action, value, time } = ota_action_log;
  // console.log('debug0', ota_action_log)
  // 检查 taskid 是否存在
  const task = await otaTaskRepo.findOne({ where: { id: taskid } });
  // console.log('debug1')
  if (!task) {
    console.error(`任务ID ${taskid} 不存在，无法创建 action log`);
    return; // 如果任务不存在，直接返回，不做任何操作
  }
  // console.log('debug2')
  if (!!gw_mac) {
    updateGw({ mac: gw_mac }, gatewayRepo)
  }
  if (!!wb_mac) {
    let wbArray = [{
      addr: wb_mac.toUpperCase(),
      version: fw_version?.toString(),
      name: fw_name
    }]
    // **4. 插入或更新 wb_mac 对应的 wristband 表**
    updateWristband(wbArray, wristbandRepo)
    // console.log('debug3', wbArray)
  }

  // console.log('debug4')

  // console.log('debug5')
  // **5. 创建 OTA 记录**
  const log = new ActionLogOta();
  if (taskid) {
    log.taskid = taskid || ''; // 使用传入的 taskid
    log.gw_mac = gw_mac || '';
    log.wb_mac = wb_mac || '';
    log.action = action || '';
    log.value = value?.toString() || '';
    log.time = time || new Date();
    // console.log('debug6')
    // **6. 保存到数据库 action_log**
    try {
      // console.log('debug7')
      await actionLogRepo.insert(log);
    } catch (err) {
      // console.log('debug8')
      console.log('action_log err', err);
    }
  }
}